{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python入门教程"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 一，编程环境"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. 使用VS Code + Jupyter扩展（Extensions）。\n",
    "\n",
    "2. 参考第一章实验中的内容，构建VS Code *.ipynb的开发环境。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  二，运算"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 算术运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result1 = 31.0\n",
      "result2 = 1.0\n"
     ]
    }
   ],
   "source": [
    "result1 = 1+(100-20)/4+5*2   #四则运算\n",
    "print(\"result1 =\", result1)\n",
    "\n",
    "import math\n",
    "from math import pi\n",
    "result2 = math.sin(pi/2)  #三角函数\n",
    "print(\"result2 =\", result2)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 赋值运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "val1_int=20\n",
      "val2_f=255.00\n"
     ]
    }
   ],
   "source": [
    "val1_int = 100\n",
    "val2_f = 25.5\n",
    "val1_int -= 80                # 等价于 n1=n1-80\n",
    "val2_f *= val1_int - 10       # 等价于 f1=f1*( n1 - 10 )\n",
    "print(\"val1_int=%d\" % val1_int)\n",
    "print(\"val2_f=%.2f\" % val2_f)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 位运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9|5 = 13\n"
     ]
    }
   ],
   "source": [
    "result = 9|5\n",
    "print(\"9|5 =\", result)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 比较运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "89是否大于100： False\n",
      "24*5是否大于等于76： True\n",
      "86.5是否等于86.5： True\n",
      "34是否等于34.0： True\n",
      "False是否小于True： True\n",
      "True是否等于True： False\n"
     ]
    }
   ],
   "source": [
    "print(\"89是否大于100：\", 89 > 100)\n",
    "print(\"24*5是否大于等于76：\", 24*5 >= 76)\n",
    "print(\"86.5是否等于86.5：\", 86.5 == 86.5)\n",
    "print(\"34是否等于34.0：\", 34 == 34.0)\n",
    "print(\"False是否小于True：\", False < True)\n",
    "print(\"True是否等于True：\", True < True)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 三目运算符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max= 4\n"
     ]
    }
   ],
   "source": [
    "a = 3\n",
    "b = 4\n",
    "max = a if a>b else b\n",
    "print(\"max=\",max)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 逻辑运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(2>0 and 3<0 or 3<0)\n",
    "print(2>0 or 3<0 and 3<0)\n",
    "print(('test'=='Test') or 1!=1.0 and 2==2.0)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 运算符优先级"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result1 = 32\n",
      "result2 = 32\n",
      "result3 = 20\n"
     ]
    }
   ],
   "source": [
    "result1 = 4 + 4 << 2\n",
    "result2 = (4 + 4) << 2\n",
    "result3 = 4 + (4<<2)\n",
    "print(\"result1 =\", result1)\n",
    "print(\"result2 =\", result2)\n",
    "print(\"result3 =\", result3)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 三，Python语法基础"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 输入输出：输出print"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Python.\n",
      "1234\n",
      "x=1234, y=5678\n"
     ]
    }
   ],
   "source": [
    "print(\"Hello, Python.\")\n",
    "x = 1234\n",
    "print(x)  # 输出变量\n",
    "y = 5678\n",
    "print('x=%d, y=%d'%(x, y)) # 格式化输出"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 输入输出：输入input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "your name is: 高延增\n"
     ]
    }
   ],
   "source": [
    "#input 输入的都是字符串\n",
    "name = input('please input your name:')\n",
    "print(\"your name is:\", name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你的身高是：1.700000米\n"
     ]
    }
   ],
   "source": [
    "#利用float函数将字符串转换成浮点数\n",
    "height = float(input('请输入你的身高（单位：米）:')) # input得到的是一个str，需要用float函数转换\n",
    "print('你的身高是：%f米'%height)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "please input your age:2018-1999\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "19"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 利用eval函数将输入的字符串作为表达式进行计算\n",
    "age = eval(input('please input your age:'))\n",
    "age"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 基本变量类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "message  = \"Hello world\"  # 将字符串\"Hello world\"赋值给变量message\n",
    "a = 1     # 将整形1赋值给变量a\n",
    "b = 1.234 # 将浮点型1.234赋值给变量b\n",
    "Max_CONNECTIONS = 5000 # 将整型5000赋值给常量Max_CONNECTIONS"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 一行代码赋值多个变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b, c = 1, 2, \"runoob\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 数据类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>\n"
     ]
    }
   ],
   "source": [
    "a, b, c, d = 20, 5.5, True, 4+3j\n",
    "print(type(a), type(b), type(c), type(d))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 数值类型自动匹配"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>\n"
     ]
    }
   ],
   "source": [
    "a, b, c, d = 20, 5.5, True, 4+3j\n",
    "print(type(a), type(b), type(c), type(d))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lower_name is hou yueen, upper_name is HOU YUEEN,    title_name is Hou Yueen\n"
     ]
    }
   ],
   "source": [
    "name = \"hou yueen\"\n",
    "lower_name = name.lower()\n",
    "upper_name = name.upper()\n",
    "title_name = name.title()\n",
    "print(f\"lower_name is {lower_name}, upper_name is {upper_name},\\\n",
    "    title_name is {title_name}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "str"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(name)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 四，导入模块"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "import ...\n",
    "\n",
    "或 from ... import ...\n",
    "\n",
    "或 import ... as ..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2018, 9, 22, 22, 33, 50, 56469)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 以普通方式导入\n",
    "\n",
    "import datetime\n",
    "datetime.datetime.today()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2018, 9, 22, 22, 33, 52, 361536)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 导入模块中某个对象\n",
    "\n",
    "from datetime import datetime\n",
    "datetime.today()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.date(2018, 1, 1)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 导入模块中全部对象\n",
    "\n",
    "from datetime import *\n",
    "datetime.today()\n",
    "date(2018,1,1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2018, 9, 22, 22, 33, 58, 436262)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 以简写方式导入模块\n",
    "\n",
    "import datetime as dt\n",
    "dt.datetime.today()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 五，语法规则"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 标识符"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "标识符由字母、数字、下划线组成，区分大小写，不能以数字开头。以下划线开头的标识符有特殊含义。以单下划线开头的（_foo）的代表不能直接访问的类属性，以双下划线开头的（__foo）代表类的私有成员；以双下划线开头和结尾的(__foo__)代表Python里特殊方法专用的标识，如__init__() 代表类的构造函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1.9.3'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy \n",
    "numpy.__version__"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 缩进"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python的代码块不使用大括号来控制类、函数、以及其他逻辑判断，而是使用缩进来写实现代码分组。通常用四个空格来进行缩进。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "a,b = 1,2\n",
    "if a>b:\n",
    "    x = a\n",
    "else:\n",
    "    x = b\n",
    "print(x)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 注释"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "python中单行注释采用 # 开头。\n",
    "多行注释使用三个单引号(''')或三个双引号(\"\"\")。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "三引号注释\n",
    "（可以换行）\n",
    "\"\"\"\n",
    "\"单引号注释（不能换行）\"\n",
    "def my_abs(x): #绝对值函数\n",
    "    if x >= 0:\n",
    "        return(x)\n",
    "    else:\n",
    "        return(-x)\n",
    "    "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python语句中一般以新行作为为语句的结束符。\n",
    "但是我们可以使用斜杠（ \\）将一行的语句分为多行显示。\n",
    "如果有{},[],()跨行则可以不使用\\"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 1+2+3+4+5+6+7+\\\n",
    "    7+8+9+10\n",
    "b = [1,2,3,4,\n",
    "    5,6,7,8]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python可以在同一行中使用多条语句，语句之间使用分号分割。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "6\n"
     ]
    }
   ],
   "source": [
    "a=1;b=a+5\n",
    "print(a);print(b)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 六，Python数据结构概述"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "python内建的数据结构有列表，元组，字符串，字典，集合等。\n",
    "\n",
    "此外常用的还有numpy中的array，以及pandas中的dataframe和series。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 有序数据结构： list\\tuple\\str"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* list（列表），是有序集合，没有固定大小，可以通过对偏移量以及其他方法修改列表大小。列表的基本形式如：[1,2,3,4] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "appended bicycles is: ['trek', 'connondale', 'redline', 'specialized', 'giant']\n",
      "popped bicycles is: ['trek', 'connondale', 'redline', 'specialized']\n",
      "sorted bicycles is: ['connondale', 'redline', 'specialized', 'trek']\n",
      "bicycles[1:3] is f['redline', 'specialized']\n"
     ]
    }
   ],
   "source": [
    "bicycles = [\"trek\", \"connondale\", \"redline\", \"specialized\"]\n",
    "bicycles.append(\"giant\")\n",
    "print(f\"appended bicycles is: {bicycles}\")\n",
    "bicycles.pop()\n",
    "print(f\"popped bicycles is: {bicycles}\")\n",
    "bicycles.sort()\n",
    "print(f\"sorted bicycles is: {bicycles}\")\n",
    "print(f\"bicycles[1:3] is f{bicycles[1:3]}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 元组tuple的不可变性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tuple_var3 is: (1, 3, 5, 'xyz', 3, 4, 5)\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32md:\\LocalDocs\\ai_textbook_demos\\demos\\Chap02\\chap02_Python_tutorial.ipynb Cell 62\u001b[0m in \u001b[0;36m<cell line: 5>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      <a href='vscode-notebook-cell:/d%3A/LocalDocs/ai_textbook_demos/demos/Chap02/chap02_Python_tutorial.ipynb#Y454sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m tuple_var3 \u001b[39m=\u001b[39m tuple_var1 \u001b[39m+\u001b[39m tuple_var2\n\u001b[0;32m      <a href='vscode-notebook-cell:/d%3A/LocalDocs/ai_textbook_demos/demos/Chap02/chap02_Python_tutorial.ipynb#Y454sZmlsZQ%3D%3D?line=3'>4</a>\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mtuple_var3 is: \u001b[39m\u001b[39m{\u001b[39;00mtuple_var3\u001b[39m}\u001b[39;00m\u001b[39m\"\u001b[39m)\n\u001b[1;32m----> <a href='vscode-notebook-cell:/d%3A/LocalDocs/ai_textbook_demos/demos/Chap02/chap02_Python_tutorial.ipynb#Y454sZmlsZQ%3D%3D?line=4'>5</a>\u001b[0m tuple_var1[\u001b[39m1\u001b[39;49m] \u001b[39m=\u001b[39m \u001b[39m3\u001b[39m\n",
      "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "tuple_var1 = (1,3,5, 'xyz')\n",
    "tuple_var2 = (3,4,5)\n",
    "tuple_var3 = tuple_var1 + tuple_var2\n",
    "print(f\"tuple_var3 is: {tuple_var3}\")\n",
    "tuple_var1[1] = 3"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "tuple（元组），是有序集合，是不可变的，可以进行组合和复制运算后会生成一个新的元组。元组的基本形式比如：(1,3,6,10) \n",
    "\n",
    "str（字符串），也是有序集合，字符串的基本形式比如：’hello'。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "list1[0] is: 1\n",
      "Now, list1 is: ['new', 'python', 3, 3.14]\n"
     ]
    }
   ],
   "source": [
    "list1 = [1,'python',3, 3.14]\n",
    "print(f\"list1[0] is: {list1[0]}\")\n",
    "list1[0] = 'new'\n",
    "print(f\"Now, list1 is: {list1}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 无序数据结构：集合set、字典dict"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "set（集合），是一个无序不重复元素的集。\n",
    "基本功能包括关系运算和消除重复元素。集合的基本形式如：\n",
    "{'apple','orange','banana'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "set_var1 is: {'banana', 'cherry', 'apple', 'grape'}\n",
      "set_var2 is: {'orange', 'banana', 'apple'}\n",
      "set_var3 is: {'banana', 'apple'}\n",
      "set_var4 is: {'orange', 'grape', 'banana', 'cherry', 'apple'}\n"
     ]
    }
   ],
   "source": [
    "set_var1 = {\"apple\", \"banana\", \"cherry\"}\n",
    "set_var1.add(\"grape\")\n",
    "set_var2 = {\"apple\", \"banana\", \"orange\"}\n",
    "set_var3 = set_var1 & set_var2\n",
    "set_var4 = set_var1 | set_var2\n",
    "print(f\"set_var1 is: {set_var1}\")\n",
    "print(f\"set_var2 is: {set_var2}\")\n",
    "print(f\"set_var3 is: {set_var3}\")\n",
    "print(f\"set_var4 is: {set_var4}\")\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "dict（字典）是无序的键：值对 (key:value 对)的集合。\n",
    "键必须是互不相同的(在同一个字典之内)。\n",
    "字典的基本形式如：{'ICBC': 95588, 'BOC': 95566}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_var['color'] is: red.\n"
     ]
    }
   ],
   "source": [
    "dict_var = {\"color\":\"red\", \"points\":5}\n",
    "print(f\"dict_var[\\'color\\'] is: {dict_var['color']}.\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* dict添加键值对、修改字典已有键的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "old dict_var is: {'color': 'red', 'points': 5}\n",
      "new dict_var is: {'color': 'blue', 'points': 5, 'x_point': 100}\n",
      "dict_var deleted is: {'color': 'blue', 'x_point': 100}\n"
     ]
    }
   ],
   "source": [
    "dict_var = {\"color\":\"red\", \"points\":5}\n",
    "print(f\"old dict_var is: {dict_var}\")\n",
    "dict_var['color'] = 'blue'\n",
    "dict_var['x_point'] = 100\n",
    "print(f\"new dict_var is: {dict_var}\")\n",
    "del dict_var['points']\n",
    "print(f\"dict_var deleted is: {dict_var}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* dict的get用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "red\n",
      "No z_point value assigned.\n"
     ]
    }
   ],
   "source": [
    "dict_var = {\"color\": \"red\", \"points\": 5, \"x_point\": 100, \"y_point\": 50}\n",
    "color = dict_var.get(\"color\", \"No color value assigned.\")\n",
    "z_point = dict_var.get(\"z_point\", \"No z_point value assigned.\")\n",
    "print(color)\n",
    "print(z_point)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* for循环遍历字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "key is: color, value is: red.\n",
      "key is: points, value is: 5.\n",
      "key is: x_point, value is: 100.\n",
      "key is: y_point, value is: 50.\n"
     ]
    }
   ],
   "source": [
    "dict_var = {\"color\": \"red\", \"points\": 5, \"x_point\": 100, \"y_point\": 50}\n",
    "for k, v in dict_var.items():\n",
    "    print(f\"key is: {k}, value is: {v}.\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 条件语句if"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在编程过程中，通常需要通过对一些条件进行判断，进而决定程序执行符合条件的相应语句。和其他语言一样，python的if语句可以检查程序当前的状态，并采取相应的措施。\n",
    "if语句一般有if结构、if-else结构、if-elif-else结构三种，示例代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You are a kid\n"
     ]
    }
   ],
   "source": [
    "age = int(input(\"input your age please: \"))\n",
    "if age < 2:\n",
    "    print(\"You are a baby\")\n",
    "elif age < 12:\n",
    "    print(\"You are a kid\")\n",
    "elif age < 30:\n",
    "    print(\"You are a young people\")\n",
    "elif age < 60:\n",
    "    print(\"You are a middle-aged people\")\n",
    "else:\n",
    "    print(\"You are a old people\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 循环语句for、while"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python中，for循环用于迭代序列（即列表，元组，字典，集合或字符串）。这与其他编程语言中的 for 关键字不太相似，而是更像其他面向对象编程语言中的迭代器方法。通过使用 for 循环，我们可以为列表、元组、集合中的每个项目执行一组语句。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "apple\n",
      "banana\n"
     ]
    }
   ],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "for x in fruits:\n",
    "    print(x) \n",
    "    if x == \"banana\":\n",
    "        break"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "for 和range(n)共用，实现n次循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "for i in range(3):\n",
    "    print(i)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "while循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "number = 0\n",
    "while number < 3:\n",
    "\tnumber += 1\n",
    "\tprint(number)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 七，列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[0, 1, 2], [1, 2, 3]]"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 1,建立列表\n",
    "\n",
    "fruits = ['apple','orange','banana']\n",
    "a = list(range(1,11,2))\n",
    "b = [2**i  for i in range(5)]\n",
    "c = [[i+j for i in range(3)] for j in range(2)]\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 3, 5, 7, 9]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[1, 3, 5]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2,访问列表\n",
    "# 列表支持下标访问和切片访问\n",
    "\n",
    "print(a)\n",
    "a[0]\n",
    "a[-1]\n",
    "a[-2]\n",
    "\n",
    "a[0:3]\n",
    "a[0:3:2]\n",
    "a[0:]\n",
    "a[:-2]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 3,修改列表\n",
    "\n",
    "a[0] = 0\n",
    "a.remove(5)  #删除元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 7, 9]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del(a[0])\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 7, 9, 1, 2, 3]"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a + [1,2,3]  # +号对序列有拼接作用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 7, 9, 3, 7, 9, 3, 7, 9]"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a * 3  # *号有复制拷贝多份效果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[9, 7, 3]"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 4,列表常用函数\n",
    "\n",
    "len(a)\n",
    "\n",
    "max(a)\n",
    "\n",
    "min(a)\n",
    "\n",
    "sorted(a,reverse = True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 5,列表常用方法\n",
    "\n",
    "a.extend([8,10])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a.append(11)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 3, 7, 9, 8, 10, 11]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.insert(0,1)\n",
    "a"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 八，字典\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典在插入元素和查找元素方面很多时候比列表更加高效。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 1,创建字典\n",
    "\n",
    "d = {1:3,2:4,3:6}\n",
    "a = dict([('a',1),['b',2]])\n",
    "b = dict(x = 1,y = 2)\n",
    "\n",
    "D = {i:i**2 for i in range(5)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 2,字典常用操作\n",
    "\n",
    "a['a'] = 3\n",
    "a['c'] = 5\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['b', 'a', 'c'])"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_values([2, 3, 5])"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_items([('b', 2), ('a', 3), ('c', 5)])"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.items()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 2, 'c': 5}"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 3, 'c': 5, 'd': 10}"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.update({'b':3,'d':10})\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.get('e',0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.setdefault('a',4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 3, 'c': 5, 'd': 10, 'e': 4}"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.setdefault('e',4)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 3, 'c': 5, 'd': 10, 'e': 4}"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.copy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 九，字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "### 1,创建字符串\n",
    "s1 = 'I\\'m Jimmy.\\nI just use Python to say:\"hello world\"!'\n",
    "print(s1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "s2 = \"I'm Jimmy.\\nI just use Python to say:\\\"hello world\\\"!\"\n",
    "print(s2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "s3 = '''I'm Jimmy.\n",
    "I just use Python to say:\"hello world\"!'''\n",
    "print(s3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'I\\'m Jimmy.\\nI just use Python to say:\"hello world\"!'"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'12345'"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(12345)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I love Python.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "### 2,字符串拼接(+,join)\n",
    "\n",
    "s1 = \"I'm Jimmy.\"\n",
    "s2 = \"I love Python.\"\n",
    "s3 = 'I just use Python to say:\"hello world\"!'\n",
    "\n",
    "s = s1 + '\\n' + s2 + '\\n' + s3\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I love Python.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "print('\\n'.join([s1,s2,s3]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abcabcabcabcabc'"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"abc\" * 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abcdefxyz'"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 3,清洗字符串(replace,strip)\n",
    "\n",
    "\"$$$abcdef$$xyz\".replace('$','')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abc123'"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\\nabc123\\t\".strip()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Jimmy', '18', 'male']"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Jimmy\\t18\\tmale\".split('\\t')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm 19 years old. My weight is 60.50 kg. I like travelling\n"
     ]
    }
   ],
   "source": [
    "### 4,格式化字符串(%或format)\n",
    "age = 19\n",
    "weight = 60.5\n",
    "hobby = 'travelling'\n",
    "# %d表示整数， %f表示浮点数， %s表示字符串\n",
    "\n",
    "fs = \"I'm %d years old. My weight is %.2f kg. I like %s\" %(age,weight,hobby)\n",
    "print(fs)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I'm 19 years old. My weight is 60.50 kg. I like travelling\""
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fs = \"I'm {} years old. My weight is {:.2f} kg. I like {}\" .format(age,weight,hobby)\n",
    "fs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十，元组 tuple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1,创建元组\n",
    "t = (1,2,3)\n",
    "t0 = ()\n",
    "t1 = (1,)\n",
    "x = 1,2\n",
    "\n",
    "y = tuple([1,2,3])\n",
    "z = tuple('abc')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2,使用元组\n",
    "\n",
    "t.count(1)\n",
    "t.index(3)\n",
    "\n",
    "#序列解包\n",
    "a,b = 1,2\n",
    "t1,t2,t3 = [1,2,3]\n",
    "\n",
    "#元组可以作为字典key\n",
    "\n",
    "d = {(1,2):4}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{(1, 2): 4}"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3,浅拷贝与深拷贝\n",
    "\n",
    "t2 = t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l = [1,2,3]\n",
    "l3 = l.copy() # 深拷贝开辟新的内存空间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l3[0] = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 3]"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3]"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2 = l   #浅拷贝只是原来对象的一个别名。\n",
    "l2[0] = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 3]"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 3]"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十一，集合 Set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1，创建集合\n",
    "\n",
    "s = {1,2,3}\n",
    "s0 = set()\n",
    "\n",
    "s3 = {x**2 for x in range(3)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{0, 1, 4}"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2，使用集合\n",
    "\n",
    "#去除重复对象，求交集，并集，补集等操作\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = [1,2,3,3,5,6,7,5,8,7]\n",
    "\n",
    "len(set(a))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s1 = {1,2,3,6,7}\n",
    "s2 = {2,5,8,10}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{2}"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s1 & s2 #交集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 5, 6, 7, 8, 10}"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s1 | s2 #并集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 3, 6, 7}"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s1.difference(s2)  #广义补集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十二，条件语句if "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 1, if语句\n",
    "a,b = 3,2\n",
    "\n",
    "if a>b:\n",
    "    x = a\n",
    "else:\n",
    "    x = b\n",
    "    \n",
    "#if...elif..elif...else...\n",
    "\n",
    "y = a if a>b else b\n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2, 逻辑运算符\n",
    "\n",
    "2>3\n",
    "1+2<100\n",
    "3 == 4-1\n",
    "2 != 3\n",
    "\n",
    "not 2==3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{3, 4}"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 3, and和or\n",
    "\n",
    "2>3 and 4<5\n",
    "2>3 or 4<5\n",
    "\n",
    "x = [] or [1,2,3] or {}  #短路计算，注意空字典和空列表为false\n",
    "y = 50 and {1} and {3,4} \n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(False, True, True)"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool(''),bool([1]),bool(-1)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十三，循环语句 for，while"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "5\n",
      "4\n",
      "3\n",
      "b : 2\n",
      "a : 1\n",
      "c : 3\n"
     ]
    }
   ],
   "source": [
    "# 1,for循环\n",
    "\n",
    "l = [1,2,5,4,3]\n",
    "for i in l:\n",
    "    print(i)\n",
    "\n",
    "d = {'a':1,'b':2,'c':3}\n",
    "for k,v in d.items():\n",
    "    print(k,':',v)   \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "#求 l中最大的元素\n",
    "l = [1,2,5,4,3]\n",
    "max(l)\n",
    "max_l = l[0]\n",
    "for i in l:\n",
    "    max_l = i if i>max_l else max_l\n",
    "print(max_l)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('b', 2), ('a', 1), ('c', 3)]"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(d.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5050 101\n"
     ]
    }
   ],
   "source": [
    "# 2,while循环\n",
    "\n",
    "#求1+2+3+...+100\n",
    "s,i = 0,1\n",
    "while i<=100:\n",
    "    s = s + i\n",
    "    i = i + 1\n",
    "print(s,i)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "\n",
      "helloworld"
     ]
    }
   ],
   "source": [
    "# 3,循环控制continue,break\n",
    "\n",
    "s = 'hello world'\n",
    "\n",
    "# break跳出本层循环\n",
    "for i in s:\n",
    "    if i ==' ':\n",
    "        break\n",
    "    print(i,end = '')\n",
    "\n",
    "print('\\n')\n",
    "\n",
    "# continue跳出本次循环\n",
    "for i in s:\n",
    "    if i ==' ':\n",
    "        continue\n",
    "    print(i,end = '')\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十四，函数"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 函数的参数，位置参数、关键字参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hello_user(first_name, last_name, middle_name=\"\"):\n",
    "    print(f\"Hello {first_name.title()}{middle_name.title()}{last_name.title()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello William Clinton \n",
      "Hello William JaffersonClinton \n",
      "Hello William JaffersonClinton \n"
     ]
    }
   ],
   "source": [
    "hello_user(\"william \", \"clinton \")  # 位置参数\n",
    "hello_user(\"william \", \"clinton \", \"jafferson\") # 位置参数+关键字参数\n",
    "hello_user(\"William \", \"Clinton \", middle_name = \"Jafferson\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 函数可变长参数"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可变长位置参数示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 2, 3, 4, 5, 6)\n"
     ]
    }
   ],
   "source": [
    "def demo(*p):\n",
    "    print(p)\n",
    "\n",
    "demo(1,2,3,4,5,6)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可变长关键字参数函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'x': 1, 'y': 2, 'z': 3}\n"
     ]
    }
   ],
   "source": [
    "def demo(**p):\n",
    "\tprint(p)\n",
    "\n",
    "demo(x=1,y=2,z=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#1,函数参数：普通参数,默认参数,可变参数,关键字参数\n",
    "#普通参数(位置参数)\n",
    "\n",
    "def my_abs(x):\n",
    "    return(x if x>=0 else -x)\n",
    "\n",
    "my_abs(-5)\n",
    "my_abs(x = 5)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "125"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#默认参数 n(参数缺失时赋默认值)\n",
    "\n",
    "def my_power(x,n = 2):\n",
    "    return(x**n)\n",
    "\n",
    "my_power(5)\n",
    "my_power(x = 5,n = 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#可变参数 *args(可以传入不定长度参数序列，元组或列表)\n",
    "\n",
    "def my_sum(*args):\n",
    "    s = 0\n",
    "    for i in args:\n",
    "        s = s + i\n",
    "    return(s)\n",
    "my_sum(1,2,3)\n",
    "my_sum()\n",
    "my_sum(*(1,2,3))\n",
    "my_sum(*[1,2,3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'age': 18, 'grade': '13', 'hometown': 'London', 'name': 'Jim'}"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#关键字参数 **kv(可以传入字典)\n",
    "\n",
    "def student(name,age,**kv):\n",
    "    d = {'name':name,'age':age}\n",
    "    d.update(kv)\n",
    "    return(d)\n",
    "\n",
    "student('LiLei',19,grade = '13',gender = 'male')\n",
    "Jim = {'name':'Jim','age':18,'grade':'13','hometown':'London'}\n",
    "student(**Jim)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6765"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#2,递归函数\n",
    "#递归函数调用自身\n",
    "\n",
    "def fib(n):\n",
    "    if n in [1,2]:\n",
    "        return(1)\n",
    "    else:\n",
    "        return(fib(n-1) + fib(n-2))\n",
    "fib(20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#3,装饰器\n",
    "\n",
    "#装饰器在不更改函数代码前提下赋予函数额外的功能\n",
    "#通常把函数非核心逻辑如插入日志、权限校验、性能测试放在装饰器中\n",
    "\n",
    "import time\n",
    "def runtime(func):\n",
    "    def wrapper(*args,**kv):\n",
    "        tic = time.time()\n",
    "        ans = func(*args,**kv)\n",
    "        toc = time.time()\n",
    "        print('{} is called. {}s used'.\n",
    "              format(func.__name__,toc-tic))\n",
    "        return(ans)\n",
    "    return(wrapper)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@runtime\n",
    "def my_sum(*args):\n",
    "    s = 0\n",
    "    for i in args:\n",
    "        s = s + i\n",
    "    return(s)\n",
    "# @runtime是一个语法糖\n",
    "# 相当于 my_sum = runtime(my_sum)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "my_sum is called. 1.8358230590820312e-05s used\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "4950"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_sum(*range(100))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "my_sum is called. 3.5762786865234375e-06s used\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_sum(1,2,3)  #相当于 runtime(my_sum)(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fib is called. 1.1920928955078125e-06s used\n",
      "fib is called. 1.1920928955078125e-06s used\n",
      "fib is called. 5.269050598144531e-05s used\n",
      "fib is called. 1.1920928955078125e-06s used\n",
      "fib is called. 7.557868957519531e-05s used\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@runtime\n",
    "def fib(n):\n",
    "    if n in [1,2]:\n",
    "        return(1)\n",
    "    else:\n",
    "        return(fib(n-1) + fib(n-2))\n",
    "fib(4)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十五，lambda匿名函数"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "lambda只是一个表达式，适合定义较为简单的函数。\n",
    "\n",
    "lambda函数的定义语法是：\n",
    "\n",
    "fun = lambda 参数序列：返回值表达式\n",
    "\n",
    "一般来说通过使用lambda匿名函数可以节约程序开支并加快运行速度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_abs = lambda x: x if x>=0 else -x\n",
    "my_abs(-5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "25"
      ]
     },
     "execution_count": 106,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_power = lambda x,n=2:x**n\n",
    "my_power(-5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-125"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(lambda x,n=2:x**n)(-5,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_sum = lambda *args:sum(args)\n",
    "my_sum(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'age': 18, 'grade': '13', 'name': 'LiLei'}"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "student = lambda name,age,**kv:dict(name = name,age = age,**kv)\n",
    "student('LiLei',18,grade = '13')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'age': 18, 'grade': '13', 'name': 'LiLei'}"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = {'name':'LiLei','age':18}\n",
    "d.update({'grade':'13'})\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "NoneType"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(d.update({'grade':'13'}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "55"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fib = lambda n: 1 if n in [1,2] else fib(n-1)+fib(n-2)\n",
    "fib(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  十六，高阶函数"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以函数为参数的函数叫做高阶函数。常用的内置高阶函数有：map,reduce,filter。\n",
    "\n",
    "高阶函数和匿名函数搭配使用,堪称绝配。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 4, 9, 16]"
      ]
     },
     "execution_count": 113,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1,map将一个函数作用到一个序列或者多个序列配对\n",
    "#map英文单词原意:映射\n",
    "\n",
    "list(map(lambda x:x**2,[1,2,3,4]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a1', 'b2', 'c3']"
      ]
     },
     "execution_count": 114,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(map(lambda x,y:x+y,'abc','123'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2,reduce 将一个带有两个参数的函数依次迭代作用到一个序列\n",
    "#reduce英文单词原意：减少\n",
    "#reduce(f,[a,b,c,d]) = f(f(f(a,b),c),d)\n",
    "\n",
    "from functools import reduce\n",
    "reduce(lambda x,y:x+y,[1,2,3,4])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2]"
      ]
     },
     "execution_count": 116,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 3,filter 根据规则过滤序列中的元素\n",
    "#filter英文单词愿意：过滤\n",
    "\n",
    "list(filter(lambda x:x>0,[-1,-2,1,2]))\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十七，Python推导式"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python中的推导式是我最喜爱的一类语法规则，没有之一。\n",
    "\n",
    "Python推导式可以生成列表,字典和集合。\n",
    "\n",
    "Python推导式虽然简单，但表达能力很强，可以实现map,filter等功能,并且可以多重遍历。\n",
    "\n",
    "淋漓尽致地体现了Python语言的simple,readable,powerful的特点。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('Jim', 'Mary'), ('Jim', 'Lily'), ('John', 'Mary'), ('John', 'Lily')]"
      ]
     },
     "execution_count": 117,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 1，列表推导式\n",
    "\n",
    "#生成平方数序列\n",
    "[x**2 for x in range(4)]\n",
    "\n",
    "#求序列的绝对值\n",
    "l = [-1,-2,3,4,-2]\n",
    "[x if x>0 else -x for x in l]\n",
    "\n",
    "list(map(lambda x:x if x>0 else -x,l))\n",
    "\n",
    "#过滤序列中某些元素\n",
    "[x for x in l if x>0]\n",
    "list(filter(lambda x:x>0, l))\n",
    "\n",
    "#多重遍历\n",
    "girls = ['Mary','Lily']\n",
    "boys = ['Jim','John']\n",
    "couples = [(b,g) for b in boys for g in girls]\n",
    "couples\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1: 'Spring', 2: 'Summer', 3: 'Autumn', 4: 'Winter'}"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2,字典推导式\n",
    "\n",
    "seasons = ['Spring','Summer','Autumn','Winter']\n",
    "d = {k:v for k,v in enumerate(seasons,start = 1)} \n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(1, 'Spring'), (2, 'Summer'), (3, 'Autumn'), (4, 'Winter')]"
      ]
     },
     "execution_count": 119,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(enumerate(seasons,start = 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 1, 'b': 2, 'c': 3}"
      ]
     },
     "execution_count": 120,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keys = ['a','b','c']\n",
    "values = [1,2,3]\n",
    "D = {k:v for k,v in zip(keys,values)}\n",
    "D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 3,集合推导式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3}"
      ]
     },
     "execution_count": 121,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "{abs(x) for x in [-1,-2,1,2,3]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{2, 4}"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 求两个集合的交集\n",
    "a = {1,2,5,4}\n",
    "b = {2,4,6,8}\n",
    "\n",
    "a.intersection(b)\n",
    "\n",
    "{x for x in a if x in b}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十八，类和对象"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1，面向对象基本概念\n",
    "\n",
    "* 什么是面向对象编程？\n",
    "\n",
    "POP: Process Oriented Programming. 程序被看成一系列命令的依次执行。基本封装形式为函数。 \n",
    "设计函数的基本要点是 IPO：输入Input ——> 处理Process ——> 输出Output.\n",
    "\n",
    "OOP: Object Oriented Programming. 程序被看成一系列对象的相互作用。基本的封装形式是类。\n",
    "设计类的基本要点是 RPM: 关系 Relation， 属性Property，方法 Method.\n",
    "类和类之间常用的方法包括：is（继承关系）, has（包含关系）, use（使用关系）\n",
    "\n",
    "\n",
    "* 面向对象基本术语？\n",
    "\n",
    "类： class, 抽象数据结构，数据和算法的封装。如：定义一个类：dog。\n",
    "\n",
    "对象： object, 类的实例。如：dog类的一个实例：点点dot。\n",
    "\n",
    "属性：properties，和对象关联的数据部分。如：weight 体重，breed 品种。\n",
    "\n",
    "方法：methods，和对象关联的算法部分。如：run(), eat(), bark()。\n",
    "\n",
    "\n",
    "* 面向对象编程的优点？\n",
    "\n",
    "容易使用： 封装，奇妙的句点符号。\n",
    "\n",
    "容易扩展： 继承，多态。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 2,创建类和对象\n",
    "\n",
    "class Dog(object):\n",
    "    # __init__为构造函数\n",
    "    def __init__(self,name,weight,breed,age):\n",
    "        self.name = name\n",
    "        self.weight = weight\n",
    "        self.breed = breed\n",
    "        \n",
    "        # __age为私有属性\n",
    "        self.__age = age\n",
    "    \n",
    "    def run(self):\n",
    "        print('%s is running...'%(self.name))\n",
    "        \n",
    "    def bark(self):\n",
    "        print('Bowwow,Bowwow,Bowwow...')\n",
    "        \n",
    "    def eat(self,food):\n",
    "        print('%s is eating %s...'%(self.name,food))\n",
    "        \n",
    "    def sleep(self):\n",
    "        print('Zzz...Zzz...Zzz...')\n",
    "    \n",
    "    # __think为私有方法\n",
    "    def __think(self):\n",
    "        print('I feel myself a hero and very handsome !')\n",
    "        \n",
    "    # bark公有方法可以调用__think私有方法\n",
    "    def bark(self, sound = 'Woof!'):\n",
    "        self.__think()\n",
    "        print(sound)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "snoopy is running...\n",
      "I feel myself a hero and very handsome !\n",
      "Woof!\n",
      "snoopy is eating meat...\n",
      "Zzz...Zzz...Zzz...\n",
      "I feel myself a hero and very handsome !\n",
      "Woof!\n"
     ]
    }
   ],
   "source": [
    "snoopy = Dog('snoopy',3,'Husky',4)# 实例化一个对象\n",
    "#调用公有属性和公有方法\n",
    "snoopy.breed\n",
    "snoopy.run()\n",
    "snoopy.bark()\n",
    "snoopy.eat('meat')\n",
    "snoopy.sleep()\n",
    "snoopy.bark()\n",
    "\n",
    "#私有属性和私有方法不能够直接在类外部访问, 否则会报错。\n",
    "# snoopy.__age\n",
    "# snoopy.__think()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### BullDog继承Dog"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "class BullDog(Dog):\n",
    "\tdef bark(self, sound = \"Grr!\"):\n",
    "\t\tprint(sound)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Grr!\n"
     ]
    }
   ],
   "source": [
    "SnoopyBullDog = BullDog('snoopy',3,'Husky',4)\n",
    "SnoopyBullDog.bark()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "### 3,获取对象信息\n",
    "\n",
    "#python中万物皆对象\n",
    "\n",
    "# type查看对象类别\n",
    "\n",
    "type(1),type(False),type(snoopy),type(len),type([1,2,3])\n",
    "\n",
    "# isinstance 测试某个对象是否属于某个类\n",
    "isinstance({1,2,3},set)\n",
    "isinstance(max,object)\n",
    "\n",
    "# object是the most base type\n",
    "print(isinstance(123,(list,str,float,int)))\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十九，封装和继承"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1,封装\n",
    "\n",
    "奇妙的句点符号：通过奇妙的句点符号可以召唤对象的属性和方法。\n",
    "私有属性和私有方法除外。\n",
    "\n",
    "公有属性和公有方法\n",
    "\n",
    "私有属性和私有方法：以双下划线开头\n",
    "\n",
    "定制属性和定制方法：以双下划线开头和双下划线结尾\n",
    "\n",
    "__init__ 构造函数,通过类名调用\n",
    "__str__  通过str函数调用\n",
    "__len__ 通过len函数调用\n",
    "……\n",
    "\n",
    "类属性和类方法：在__init__外部定义的为类属性,\n",
    "第一个参数不是self参数的方法为类方法。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Animal(object):\n",
    "    \n",
    "    #类属性\n",
    "    home = 'earth'\n",
    "    \n",
    "    #类方法\n",
    "    def dream():\n",
    "        print('No deal, no hurt!')\n",
    "        \n",
    "    #定制方法\n",
    "    def __str__(self):\n",
    "        return('An animal named %s'%self.name)\n",
    "        \n",
    "    def __init__(self,name,weight,breed,age):\n",
    "        \n",
    "        self.name = name\n",
    "        self.weight = weight\n",
    "        self.breed = breed\n",
    "        \n",
    "        # __age为私有属性\n",
    "        self.__age = age\n",
    "    \n",
    "    def run(self):\n",
    "        print('%s is running...'%(self.name))\n",
    "        \n",
    "        \n",
    "    def eat(self,food):\n",
    "        print('%s is eating %s...'%(self.name,food))\n",
    "        \n",
    "    def sleep(self):\n",
    "        print('Zzz...Zzz...Zzz...')\n",
    "    \n",
    "    # __think为私有方法\n",
    "    def __think(self):\n",
    "        print('I feel myself a hero and very handsome !')\n",
    "        \n",
    "    # speak公有方法可以调用私有方法\n",
    "    def speak(self,words = ''):\n",
    "        self.__think()\n",
    "        if(words):print(words)    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'earth'"
      ]
     },
     "execution_count": 127,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#类属性\n",
    "snoopy = Animal('snoopy',3,'Husky',4)\n",
    "snoopy.home\n",
    "Animal.home"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过对象能够访问，但不能够修改类属性\n",
    "#snoopy.home = 'moon'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "No deal, no hurt!\n"
     ]
    }
   ],
   "source": [
    "# 类方法只能通过类名访问，不能通过对象访问\n",
    "Animal.dream()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "snoopy is running...\n"
     ]
    }
   ],
   "source": [
    "# 通过类名也可以访问对象方法\n",
    "Animal.run(snoopy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "snoopy is running...\n"
     ]
    }
   ],
   "source": [
    "snoopy.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'An animal named snoopy'"
      ]
     },
     "execution_count": 132,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 定制方法有特殊的功能\n",
    "str(snoopy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abc123def'"
      ]
     },
     "execution_count": 133,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 奇妙的句点符号\n",
    "\n",
    "s = 'abc#123@def'\n",
    "\n",
    "#面向过程必须记住非常多函数名，replace,upper,find\n",
    "\n",
    "#面向对象只需要输入奇妙的句点符号后按下tab键\n",
    "s.replace('#','').replace('@','')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 134,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 135,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.__len__()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dir(s) # 查看全部可用属性和方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 2，继承\n",
    "\n",
    "#子类可以通过继承获得父类的属性和方法\n",
    "\n",
    "class Cat(Animal):\n",
    "    \n",
    "    def call(self):\n",
    "        print('MiaoMiaoMiao...')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "kitty = Cat('kitty',1,'Bose',5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MiaoMiaoMiao...\n"
     ]
    }
   ],
   "source": [
    "kitty.call()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I feel myself a hero and very handsome !\n",
      "miaow...miaow...miaow...\n"
     ]
    }
   ],
   "source": [
    "kitty.speak('miaow...miaow...miaow...')"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 二十，模块和包"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "一个.py文件就是一个模块。\n",
    "一个包含有__init__.py文件的文件夹就是一个包。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1，模块示范"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing mymodule.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile mymodule.py\n",
    "#!/usr/bin/env python3\n",
    "#-*- coding:utf-8 -*-\n",
    "\n",
    "'a test module'  #模块注释\n",
    "\n",
    "__author__ = 'Python_Ai_Road' #作者信息\n",
    "__version__ = 'v1.0' #版本信息\n",
    "\n",
    "def _Email():   #模块私有函数\n",
    "    print('lyhue1991@163.com')\n",
    "    \n",
    "\n",
    "def __WeChat_Official_Account():  #模块私有函数\n",
    "    print('Python与算法之美')\n",
    "    \n",
    "    \n",
    "def hello(person = 'world'): #公有函数\n",
    "    print('hello',person)\n",
    "    \n",
    "\n",
    "def test(): #测试代码\n",
    "    hello()\n",
    "    hello('China')\n",
    "    print('Contact to me:',end = '\\t')\n",
    "    _Email()\n",
    "    print('Learn more with me:', end = '\\t')\n",
    "    __WeChat_Official_Account()\n",
    "    \n",
    "\n",
    "#当直接运行该模块时，执行测试代码，而引入模块时不执行测试代码。\n",
    "if __name__ == '__main__':\n",
    "    test()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mymodule\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on module mymodule:\n",
      "\n",
      "NAME\n",
      "    mymodule - a test module\n",
      "\n",
      "FUNCTIONS\n",
      "    hello(person='world')\n",
      "    \n",
      "    test()\n",
      "\n",
      "VERSION\n",
      "    v1.0\n",
      "\n",
      "AUTHOR\n",
      "    Python_Ai_Road\n",
      "\n",
      "FILE\n",
      "    /home/jquser/mymodule.py\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(mymodule)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python_Ai_Road'"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mymodule.__author__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'a test module'"
      ]
     },
     "execution_count": 146,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mymodule.__doc__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world\r\n",
      "hello China\r\n",
      "Contact to me:\tlyhue1991@163.com\r\n",
      "Learn more with me:\tPython与算法之美\r\n"
     ]
    }
   ],
   "source": [
    "!python mymodule.py"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2，包示范\n",
    "* 用jupyter运行时有点问题，需要单独新建文件夹、新建python文件来测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir Animal"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/__init__.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/__init__.py\n",
    "#!/usr/bin/env python3\n",
    "#-*- coding:utf-8 -*-\n",
    "\n",
    "'Animal module for fun!'  #模块注释\n",
    "__author__ = 'Python_Ai_Road' #作者信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/Animal.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/Animal.py\n",
    "class Animal(object):\n",
    "    def __init__(self,name):\n",
    "        self.name = name\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/Dog.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/Dog.py\n",
    "from Animal.Animal import Animal\n",
    "class Dog(Animal):\n",
    "    def call(self):\n",
    "        print('bowwow...bowwow...bowwow...')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/Cat.py\n"
     ]
    },
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: 'Animal/Cat.py'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32mc:\\Users\\gao\\Desktop\\Python学习\\PythonAiRoad-master\\3小时Python入门.ipynb Cell 214\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> <a href='vscode-notebook-cell:/c%3A/Users/gao/Desktop/Python%E5%AD%A6%E4%B9%A0/PythonAiRoad-master/3%E5%B0%8F%E6%97%B6Python%E5%85%A5%E9%97%A8.ipynb#Y423sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m get_ipython()\u001b[39m.\u001b[39;49mrun_cell_magic(\u001b[39m'\u001b[39;49m\u001b[39mwritefile\u001b[39;49m\u001b[39m'\u001b[39;49m, \u001b[39m'\u001b[39;49m\u001b[39mAnimal/Cat.py\u001b[39;49m\u001b[39m'\u001b[39;49m, \u001b[39m\"\u001b[39;49m\u001b[39mfrom Animal.Animal import Animal\u001b[39;49m\u001b[39m\\n\u001b[39;49;00m\u001b[39mclass Cat(Animal):\u001b[39;49m\u001b[39m\\n\u001b[39;49;00m\u001b[39m    def call(self):\u001b[39;49m\u001b[39m\\n\u001b[39;49;00m\u001b[39m        print(\u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39mmiaow...miaow...miaow...\u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39m)\u001b[39;49m\u001b[39m\\n\u001b[39;49;00m\u001b[39m\"\u001b[39;49m)\n",
      "File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python39\\site-packages\\IPython\\core\\interactiveshell.py:2358\u001b[0m, in \u001b[0;36mInteractiveShell.run_cell_magic\u001b[1;34m(self, magic_name, line, cell)\u001b[0m\n\u001b[0;32m   2356\u001b[0m \u001b[39mwith\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mbuiltin_trap:\n\u001b[0;32m   2357\u001b[0m     args \u001b[39m=\u001b[39m (magic_arg_s, cell)\n\u001b[1;32m-> 2358\u001b[0m     result \u001b[39m=\u001b[39m fn(\u001b[39m*\u001b[39margs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs)\n\u001b[0;32m   2359\u001b[0m \u001b[39mreturn\u001b[39;00m result\n",
      "File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python39\\site-packages\\IPython\\core\\magics\\osm.py:853\u001b[0m, in \u001b[0;36mOSMagics.writefile\u001b[1;34m(self, line, cell)\u001b[0m\n\u001b[0;32m    850\u001b[0m     \u001b[39mprint\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mWriting \u001b[39m\u001b[39m%s\u001b[39;00m\u001b[39m\"\u001b[39m \u001b[39m%\u001b[39m filename)\n\u001b[0;32m    852\u001b[0m mode \u001b[39m=\u001b[39m \u001b[39m'\u001b[39m\u001b[39ma\u001b[39m\u001b[39m'\u001b[39m \u001b[39mif\u001b[39;00m args\u001b[39m.\u001b[39mappend \u001b[39melse\u001b[39;00m \u001b[39m'\u001b[39m\u001b[39mw\u001b[39m\u001b[39m'\u001b[39m\n\u001b[1;32m--> 853\u001b[0m \u001b[39mwith\u001b[39;00m io\u001b[39m.\u001b[39;49mopen(filename, mode, encoding\u001b[39m=\u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39mutf-8\u001b[39;49m\u001b[39m'\u001b[39;49m) \u001b[39mas\u001b[39;00m f:\n\u001b[0;32m    854\u001b[0m     f\u001b[39m.\u001b[39mwrite(cell)\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'Animal/Cat.py'"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/Cat.py\n",
    "from Animal.Animal import Animal\n",
    "class Cat(Animal):\n",
    "    def call(self):\n",
    "        print('miaow...miaow...miaow...')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on package Animal:\n",
      "\n",
      "NAME\n",
      "    Animal - Animal module for fun!\n",
      "\n",
      "PACKAGE CONTENTS\n",
      "    Animal\n",
      "    Cat\n",
      "    Dog\n",
      "\n",
      "AUTHOR\n",
      "    Python_Ai_Road\n",
      "\n",
      "FILE\n",
      "    /home/jquser/Animal/__init__.py\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import Animal\n",
    "help(Animal)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bowwow...bowwow...bowwow...\n"
     ]
    }
   ],
   "source": [
    "from Animal.Dog import Dog\n",
    "snoopy = Dog('snoopy')\n",
    "snoopy.call()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "miaow...miaow...miaow...\n"
     ]
    }
   ],
   "source": [
    "from Animal.Cat import Cat\n",
    "kitty = Cat('kitty')\n",
    "kitty.call()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 参考\n",
    "\n",
    "* https://github.com/lyhue1991/PythonAiRoad/blob/master/3%E5%B0%8F%E6%97%B6Python%E5%85%A5%E9%97%A8.ipynb\n",
    "* http://c.biancheng.net/view/2183.html"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](Python与算法之美.png)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.13 ('ai_textbook')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "vscode": {
   "interpreter": {
    "hash": "b588930fc60eaaede1f012d63146846ff2d52ca36ecacf26d634dd660f785639"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
